package cn.exempale.mscapplication.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import cn.exempale.mscapplication.R;
import cn.exempale.mscapplication.databinding.ItemTaskBinding;
import cn.exempale.mscapplication.emnus.ProgressType;
import cn.exempale.mscapplication.model.db.entity.TaskEntity;

public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.TaskViewHolder> {

    private Context context;
    private List<TaskEntity> tasks;

    public TaskAdapter(Context context) {
        this.context = context;
        this.tasks = new ArrayList<>();
    }

    public void setTasks(List<TaskEntity> tasks) {
        this.tasks = tasks;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public TaskViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);
        ItemTaskBinding binding = DataBindingUtil.inflate(inflater, R.layout.item_task, parent, false);
        return new TaskViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull TaskViewHolder holder, int position) {
        holder.binding.setTask(tasks.get(position));
        holder.binding.setClick(object -> {
            TaskEntity taskEntity = (TaskEntity) object;
            ProgressType type = ProgressType.match(taskEntity.getProgressStatus());
            if (type != ProgressType.TRANSFER_UPLOAD)
                return;
            Intent intent = new Intent(context, ResultActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("task", taskEntity);
            intent.putExtras(bundle);
            context.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return tasks == null ? 0 : tasks.size();
    }

    class TaskViewHolder extends RecyclerView.ViewHolder {

        private final ItemTaskBinding binding;

        public TaskViewHolder(@NonNull ItemTaskBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}
